﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace XyLicense.Library
{
    /// <summary>
    /// License帮助类
    /// </summary>
    public class LicenceHelper
    {
        public static string ReadLicenceKey(string keyfile)
        {
            var keyInfo = RegistFileHelper.ReadRegistFile(keyfile);
            if (keyInfo == null)
            {
                return string.Empty;
            }
            string[] keyInfoArr = keyInfo.Split("\r\n");
            var priKeyBase64 = keyInfoArr[0].Substring(keyInfoArr[0].IndexOf("=") + 1);
            var encrypto = keyInfoArr[1].Substring(keyInfoArr[1].IndexOf("=") + 1);
            var priKeyByte = Convert.FromBase64String(priKeyBase64);
            var priKey = Encoding.ASCII.GetString(priKeyByte);
            var info = RSAHelper.Decrypto(encrypto, priKey);
            return info;
        }

        public static bool ValidLicense()
        {
            try
            {
                var computerInfo = ComputerHelper.GetComputerDetail();
                if (string.IsNullOrEmpty(computerInfo)) 
                {
                    Console.WriteLine("获取电脑信息失败，请联系管理员！");
                    return false;
                }

                if (!File.Exists(RegistFileHelper.RegistInfofile))
                {
                    Console.WriteLine($"License授权文件不存在，复制此内容去授权：{computerInfo}");
                    return false;
                }

                var info = ReadLicenceKey(RegistFileHelper.RegistInfofile);
                var infoArr = info.Split(new char[] { '|' });

                if (computerInfo != infoArr[0])
                {
                    Console.WriteLine($"License：{infoArr[0]} 授权信息与当前电脑信息：{computerInfo} 不匹配，请复制当前电脑信息去授权！");
                    return false;
                }

                DateTime endTime = Convert.ToDateTime(infoArr[1]);
                if (DateTime.Now >= endTime)
                {
                    Console.WriteLine($"License：{infoArr[0]} 授权截止时间：【{endTime.ToString("yyyy-MM-dd HH:mm:ss")}】，授权已过期，请联系管理员重新授权！");
                    return false;
                }
                
                RegistFileHelper.WriteRegistFile($"{infoArr[0]} ，{endTime.ToString("yyyy-MM-dd HH:mm:ss")}", "XyLicense.Library.json");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"License验证失败：{ex.Message}");
                return false;
            }

            return true;
           
        }

    }
}
